//
//  LeftMenuViewController.m
//  BaishidaiKnight
//
//  Created by mac book on 2019/1/24.
//  Copyright © 2019年 sy. All rights reserved.
//

#import "LeftMenuViewController.h"
#import "LeftMenuTableViewCell.h"

#define Main_Width  (SCREEN_WIDTH/2 + Menu_CenterWidth)


@interface LeftMenuViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,strong) UITableView* tableView;

@property(nonatomic,strong) UIView* headerView;
@property(nonatomic,strong) UIButton* btnUser;
@property(nonatomic,strong) UIImageView* imageIcon;
@property(nonatomic,strong) UILabel* labelUser;
@property(nonatomic,strong) UIImageView* iconArrow;

@property(nonatomic,strong) UIView* statuView;
@property(nonatomic,strong) UIButton* btnOpen;
@property(nonatomic,strong) UIButton* btnClose;
@property(nonatomic,strong) UIButton* btnBusy;

@property(nonatomic,strong) NSArray* arrayTitle;
@property(nonatomic,strong) NSArray* arrayIcon;

@property(nonatomic,strong) NSString* cellIdentifier;

@property(nonatomic,strong) UserInfoModel *userInfoModel;

@end

@implementation LeftMenuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.arrayIcon = @[@"icon_left_task",@"icon_left_money",@"icon_left_setting"];
    self.arrayTitle = @[@"已完成的任务",@"账号余额",@"设置"];
    
    
    self.cellIdentifier = @"LeftCell";
    [self creatSubViews];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryData) name:NotificationUpdateUserAccount object:nil];
    
    
}


-(void)creatSubViews{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,  CGRectGetHeight(self.view.frame) ) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    self.tableView.scrollEnabled = NO;

    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
    [self.tableView registerClass:[LeftMenuTableViewCell class] forCellReuseIdentifier:self.cellIdentifier];
    self.tableView.backgroundColor = [UIColor colorWithRed:26/255.f green:28/255.f blue:31/255.f alpha:1.0];
    self.tableView.tableHeaderView = self.headerView;

    
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 200.f);
    [self.headerView addSubview:self.btnUser];
    [self.btnUser addSubview:self.imageIcon];
    [self.btnUser addSubview:self.labelUser];
    [self.btnUser addSubview:self.iconArrow];
    [self.headerView addSubview:self.statuView];
    [self.statuView addSubview:self.btnOpen];
    [self.statuView addSubview:self.btnClose];
    [self.statuView addSubview:self.btnBusy];
    
    
    [self layoutConstraints];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self queryData];
    
}


-(void)layoutConstraints{
    
    
    [self.btnUser mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.width.mas_equalTo(Main_Width);
        make.left.equalTo(self.view);
        make.height.mas_equalTo(160);
    }];
    
    
    [self.statuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.btnUser.mas_bottom);
        make.width.mas_equalTo(Main_Width);
        make.left.equalTo(self.btnUser);
        make.height.mas_equalTo(40);
    }];
    
    [self.imageIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(self.btnUser);
        make.left.equalTo(self.btnUser).offset(20);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    [self.labelUser mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imageIcon);
        make.right.equalTo(self.btnUser);
        make.left.equalTo(self.imageIcon.mas_right).offset(10);
        make.height.equalTo(self.imageIcon);
    }];
    
    
    
    
    UILabel *line1 = [[UILabel alloc] init];
    line1.backgroundColor  =[UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0];
    [self.statuView addSubview:line1];
    
    UILabel *line2 = [[UILabel alloc] init];
    line2.backgroundColor  =[UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0];
    [self.statuView addSubview:line2];
    
    [self.btnOpen mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.statuView);
        make.left.equalTo(self.statuView);
        make.width.mas_equalTo(self.statuView.mas_width).multipliedBy(0.33);
        
    }];
    
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.statuView);
        make.left.equalTo(self.btnOpen.mas_right);
        make.size.mas_equalTo(CGSizeMake(1, 20));
        
    }];
    
    [self.btnClose mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.width.equalTo(self.btnOpen);
        make.left.equalTo(line1.mas_right);
    }];
    
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.statuView);
        make.left.equalTo(self.btnClose.mas_right);
        make.size.equalTo(line1);
        
    }];
    
    [self.btnBusy mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.width.equalTo(self.btnOpen);
        make.left.equalTo(line2.mas_right);
    }];
    
    
}
#pragma mark - DataSource
-(void)queryData{
    
    NSDictionary* arg = @{
                          @"ince":@"get_emp_info",
                          @"emp_id":[UserHandle shareInstance].userId
                          };
    
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"data = %@",data);
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
            NSDictionary* emptyDict = [data objectForKey:@"info"];
            self.userInfoModel = [UserInfoModel mj_objectWithKeyValues:emptyDict];

            [self loadData];
        }else{
            [self alertHUD:[data objectForKey:@"fail"]];
        }
        
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
    }];
    
}

#pragma mark - tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayTitle.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LeftMenuTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell loadDataWithImage:self.arrayIcon[indexPath.row] title:self.arrayTitle[indexPath.row]];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.f;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    switch (indexPath.row) {
        case 0:
        {
            [self.sideMenuViewController hideMenuViewController];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationToFinishedTask object:nil];
        }
            break;
            
        case 1:
        {
            [self.sideMenuViewController hideMenuViewController];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationToAccount object:nil];
        }
            break;
            //            case 2:
            //            {
            //                [self.sideMenuViewController hideMenuViewController];
            //                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationMineTongJi object:nil];
            //            }
            //                break;
        case 2:
        {
            [self.sideMenuViewController hideMenuViewController];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationToSetting object:nil];
        }
            break;
        default:
            break;
    }
    
}




-(void)workTime:(UIButton*)sender{
    
    if(sender == self.btnOpen){
        if(self.btnOpen.selected){
            NSLog(@"self.btnOpen.selected:%d",self.btnOpen.selected);
        }else{
            [self changeClose:@"1"];
        }
    }else if(sender == self.btnClose){
        if(self.btnClose.selected){
            NSLog(@"btnClose:%d",self.btnClose.selected);
        }else {
//            [self changeClose:@"2"];
            
            [self callPhone];

        }
    }else{
        if(self.btnBusy.selected){
            NSLog(@"btnBusy:%d",self.btnBusy.selected);
        }else {
            [self changeClose:@"3"];
        }
    }
}

#pragma mark -
-(void)loadData{
    
    NSString* str = [NSString stringWithFormat:@"%@\n%@",self.userInfoModel.realname,self.userInfoModel.phone];
    NSMutableAttributedString* attributeStr = [[NSMutableAttributedString alloc]initWithString:str];
    self.labelUser.attributedText = attributeStr;
    
    [self.imageIcon sd_setImageWithURL:[NSURL URLWithString:self.userInfoModel.user_picture] placeholderImage:[UIImage imageNamed:@"touxiang_placeholder"]];

    
    
    
    if([ self.userInfoModel.close isEqualToString:@"1"]){
        self.btnOpen.selected = YES;
        self.btnClose.selected = NO;
        self.btnBusy.selected = NO;
        
    }else  if([self.userInfoModel.close isEqualToString:@"2"]){
        self.btnClose.selected = YES;
        self.btnOpen.selected = NO;
        self.btnBusy.selected = NO;
        
    }else{
        self.btnBusy.selected = YES;
        self.btnClose.selected = NO;
        self.btnOpen.selected = NO;
    }
}

-(void)changeClose:(NSString*)close{
    
    NSDictionary* arg = @{
                          @"ince":@"set_emp_open",
                          @"emp_id":[UserHandle shareInstance].userId,
                          @"close":close
                          };
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"data = %@",data);
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
            [self queryData];
        }else{
            [self alertHUD:[data objectForKey:@"fail"]];
        }
        
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
    }];
}

-(void)callPhone{
    
    NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",self.userInfoModel.kf_tel];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}


-(void)updateUserImage{
    
    self.navigationController.navigationBar.hidden = NO;
    UIAlertController *alertSheet = [UIAlertController alertControllerWithTitle:@"请选择头像来源" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.navigationBar.translucent = NO;
    imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.allowsEditing = YES;
    
    // 判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 设置数据源
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertSheet addAction:cameraAction];
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertSheet addAction:photoAction];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertSheet addAction:cancelAction];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alertSheet animated:YES completion:nil];
    });
    
    
}

#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"])        // 被选中的图片
    {
        // 获取照片
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        [picker dismissViewControllerAnimated:YES completion:nil];          // 隐藏视图
        
        [self commitUserAvatarDataWithImage:image];
    }
}

#pragma mark - 提交用户头像
-(void)commitUserAvatarDataWithImage:(UIImage *)image{
    

    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    
    NSDictionary* arg = @{
                          @"ince":@"arr",
                          @"emp_id":[UserHandle shareInstance].userId,
                          };

    
    
    
    [BSDNetTool requestAFURL:kHost parameters:arg imageData:imageData succeed:^(NSDictionary *data) {
        NSLog(@"上传头像 = %@",data);
        
            NSString *url = data[@"url"];
            
            NSDictionary* dic = @{
                                  @"ince":@"user_picture",
                                  @"emp_id":[UserHandle shareInstance].userId,
                                  @"img": url
                                  };
            
            [BSDNetTool PostURL:kHost  parameters:dic succeed:^(NSDictionary *data) {
                NSLog(@"data = %@",data);
                NSInteger flag = [[data objectForKey:@"status"]integerValue];
                if(flag == 1){
                    
                    self.imageIcon.image = image;
                    
                }else{
                    [self hidHUD:[data objectForKey:@"msg"]];
                }
                
            } failure:^(NSError *error) {
                [self hidHUD:@"网络异常"];
            }];

        
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];

    }];
    
}



#pragma mark - 懒加载
-(UIView *)headerView{
    if(!_headerView){
        _headerView = [[UIView alloc]init];
    }
    return _headerView;
}

-(UIButton *)btnUser{
    if(!_btnUser){
        _btnUser = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnUser.userInteractionEnabled = YES;
        [_btnUser setBackgroundImage:[UIImage imageNamed:@"icon_left_bg_header"] forState:UIControlStateNormal];
        _btnUser.adjustsImageWhenHighlighted = NO;
        [_btnUser addTarget:self action:@selector(updateUserImage) forControlEvents:UIControlEventTouchUpInside];

    }
    return _btnUser;
}

-(UIImageView *)imageIcon{
    if(!_imageIcon){
        _imageIcon = [[UIImageView alloc]init];
        [_imageIcon setImage:[UIImage imageNamed:@"icon_left_header_placeholder"]];
        _imageIcon.layer.cornerRadius = 30;
        _imageIcon.layer.masksToBounds = YES;
    }
    return _imageIcon;
}

-(UILabel *)labelUser{
    if(!_labelUser){
        _labelUser = [[UILabel alloc]init];
        _labelUser.textColor = [UIColor whiteColor];
        _labelUser.font = [UIFont systemFontOfSize:20.f];
        _labelUser.numberOfLines = 0;
        _labelUser.lineBreakMode = NSLineBreakByCharWrapping;
    }
    return _labelUser;
}

-(UIImageView *)iconArrow{
    if(!_iconArrow){
        _iconArrow = [[UIImageView alloc]init];
        [_iconArrow setImage:[UIImage imageNamed:@"icon_arrowright"]];
    }
    return _iconArrow;
}

-(UIView *)statuView{
    if(!_statuView){
        _statuView = [[UIView alloc]init];
        _statuView.backgroundColor = [UIColor colorWithRed:26/255.f green:28/255.f blue:31/255.f alpha:1.0];
        CALayer* border = [[CALayer alloc]init];
        border.frame = CGRectMake(0.f, 39.5f, SCREEN_WIDTH, 0.5f);
        border.backgroundColor = [UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0].CGColor;
        [_statuView.layer addSublayer:border];
    }
    return _statuView;
}

-(UIButton *)btnOpen{
    if(!_btnOpen){
        _btnOpen = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnOpen setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [_btnOpen setTitleColor:[UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0] forState:UIControlStateNormal];
        [_btnOpen setImage:[UIImage imageNamed:@"icon_status_open"] forState:UIControlStateSelected];
        [_btnOpen setImage:[UIImage imageNamed:@"icon_status_close"] forState:UIControlStateNormal];
        [_btnOpen setTitle:@"开工" forState:UIControlStateNormal];
        [_btnOpen setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
        [_btnOpen addTarget:self action:@selector(workTime:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnOpen;
}

-(UIButton *)btnClose{
    if(!_btnClose){
        _btnClose = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnClose setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [_btnClose setTitleColor:[UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0] forState:UIControlStateNormal];
        [_btnClose setImage:[UIImage imageNamed:@"icon_status_open"] forState:UIControlStateSelected];
        [_btnClose setImage:[UIImage imageNamed:@"icon_status_close"] forState:UIControlStateNormal];
        [_btnClose setTitle:@"收工" forState:UIControlStateNormal];
        [_btnClose setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
        [_btnClose addTarget:self action:@selector(workTime:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnClose;
}
-(UIButton *)btnBusy{
    if(!_btnBusy){
        _btnBusy = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnBusy setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [_btnBusy setTitleColor:[UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0] forState:UIControlStateNormal];
        [_btnBusy setImage:[UIImage imageNamed:@"icon_status_open"] forState:UIControlStateSelected];
        [_btnBusy setImage:[UIImage imageNamed:@"icon_status_close"] forState:UIControlStateNormal];
        [_btnBusy setTitle:@"忙碌" forState:UIControlStateNormal];
        [_btnBusy setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
        [_btnBusy addTarget:self action:@selector(workTime:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnBusy;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
